package com.gitee.cui.springcloud.service;

import java.util.concurrent.TimeUnit;

import javax.naming.Name;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

/**
 * TODO
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2022-03-07 12:09
 **/
@Service
public class PaymentService {

	/**
	 * 正常访问
	 * @param id 前端传递id
	 * @return
	 */
	public String paymentInfoOk(Long id) {
		return "线程池：" + Thread.currentThread().getName() + ", paymentInfoOk, id: " + id;
	}

	/**
	 * 访问超时
	 * @param id 前端传递id
	 * @return
	 */
	@HystrixCommand(fallbackMethod = "paymentInfoFallback", commandProperties = {
			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
	})
	public String paymentInfoTimeout(Long id) {
		int timeout = 3;
		try {
			TimeUnit.SECONDS.sleep(timeout);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// int result = 10 / 0;
		return "线程池：" + Thread.currentThread().getName() + ", paymentInfoTimeout, id: " + id;
	}

	private String paymentInfoFallback(Long id) {
		return "线程池：" + Thread.currentThread().getName() +", paymentInfoFallback, id: " + id;
	}

	// ==========以下是服务熔断的代码
	@HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback", commandProperties = {
			@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
			@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
			@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
			@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
	})
	public String paymentCircuitBreaker(Long id) {
		if (id < 0) {
			throw new RuntimeException("id不能小于0");
		}
		String serialNum = IdUtil.simpleUUID();
		return Thread.currentThread().getName() + "调用成功，流水号：" + serialNum;
	}

	private String paymentCircuitBreakerFallback(Long id) {
		return "id不能为负数，请稍后再试，id：" + id;
	}
}
